<template>
  <div class="admin-layout">
    <!-- 侧边栏 -->
    <div class="sidebar" :class="{ 
      collapsed: sidebarCollapsed, 
      'mobile-show': isMobile && mobileMenuVisible 
    }">
             <!-- 侧边栏头部 -->
       <div class="sidebar-header">
         <div class="logo" @click="goToHome">
           <div class="logo-icon">
             <el-icon><DataBoard /></el-icon>
           </div>
           <div class="logo-content" v-show="!sidebarCollapsed">
             <span class="logo-title">惠学阁管理后台</span>
           </div>
         </div>
       </div>
      
      
      
      <!-- 导航菜单 -->
      <div class="menu-section">
        <div class="menu-title" v-show="!sidebarCollapsed">
          <span>主要功能</span>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          :collapse="sidebarCollapsed"
          background-color="transparent"
          text-color="#8b949e"
          active-text-color="#ffffff"
          router
        >
          <el-menu-item index="/admin-panel/dashboard" class="menu-item">
            <div class="menu-item-content">
              <el-icon class="menu-icon"><House /></el-icon>
              <span class="menu-text">仪表盘</span>
              <div class="menu-indicator"></div>
            </div>
          </el-menu-item>
          
          <el-menu-item index="/admin-panel/users" class="menu-item">
            <div class="menu-item-content">
              <el-icon class="menu-icon"><User /></el-icon>
              <span class="menu-text">用户管理</span>
              <div class="menu-indicator"></div>
            </div>
          </el-menu-item>
          
          <el-menu-item index="/admin-panel/resources" class="menu-item">
            <div class="menu-item-content">
              <el-icon class="menu-icon"><FolderOpened /></el-icon>
              <span class="menu-text">资源管理</span>
              <div class="menu-indicator"></div>
            </div>
          </el-menu-item>
          
          <el-menu-item index="/admin-panel/comments" class="menu-item">
            <div class="menu-item-content">
              <el-icon class="menu-icon"><ChatDotSquare /></el-icon>
              <span class="menu-text">评论管理</span>
              <div class="menu-indicator"></div>
            </div>
          </el-menu-item>
        </el-menu>
      </div>
      
      
      
      <!-- 侧边栏底部信息 -->
      <div class="sidebar-footer">
        <div class="footer-content" v-show="!sidebarCollapsed">
          <div class="status-indicator">
            <div class="status-dot"></div>
            <span class="status-text">系统运行正常</span>
          </div>
          <div class="system-time">
            <el-icon><Clock /></el-icon>
            <span>{{ currentTime }}</span>
          </div>
        </div>
        
        <!-- 折叠状态下的底部 -->
        <div class="footer-collapsed" v-show="sidebarCollapsed">
          <div class="status-dot-mini"></div>
        </div>
      </div>
    </div>
    
    <!-- 主内容区域 -->
    <div class="main-container" :class="{ expanded: sidebarCollapsed }">
      <!-- 顶部导航栏 -->
      <div class="navbar">
        <div class="navbar-left">
          <el-button 
            link
            @click="toggleSidebar"
            class="sidebar-toggle"
          >
            <el-icon v-if="!sidebarCollapsed"><fold /></el-icon>
            <el-icon v-else><expand /></el-icon>
          </el-button>
          
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/admin-panel/dashboard' }">
              <el-icon><house /></el-icon>
              首页
            </el-breadcrumb-item>
            <el-breadcrumb-item v-if="breadcrumbItems.length > 0">
              {{ breadcrumbItems[breadcrumbItems.length - 1] }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="navbar-right">
          <!-- 用户信息下拉菜单 -->
          <el-dropdown @command="handleCommand" class="user-dropdown-container">
            <span class="user-dropdown">
              <el-avatar 
                :size="32" 
                :src="userInfo?.avatar" 
                class="user-avatar"
              >
                <template #default>
                  <span style="font-size: 16px;">👤</span>
                </template>
              </el-avatar>
              <span class="username">{{ userInfo?.username || 'Admin' }}</span>
              <el-icon class="arrow-down"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="logout">
                  <el-icon><switch-button /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      
      <!-- 主内容 -->
      <div class="main-content">
        <router-view />
      </div>
    </div>
    

  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import { userApi } from '@/api/user'
import { 
  House, 
  User, 
  FolderOpened, 
  ChatDotSquare, 
  Fold, 
  Expand, 
  ArrowDown, 
  SwitchButton, 
  Clock, 
  CircleCheck,
  DataBoard 
} from '@element-plus/icons-vue'

export default {
  name: 'AdminLayout',
  components: {
    House,
    User,
    FolderOpened,
    ChatDotSquare,
    Fold,
    Expand,
    ArrowDown,
    SwitchButton,
    Clock,
    CircleCheck,
    DataBoard
  },
  data() {
    return {
      sidebarCollapsed: false,
      currentTime: '',
      timeInterval: null,
      isMobile: false,
      mobileMenuVisible: false
    }
  },
  computed: {
    ...mapState(['userInfo']),
    
    activeMenu() {
      return this.$route.path
    },
    
    breadcrumbItems() {
      const routeMap = {
        '/admin-panel/dashboard': '仪表盘',
        '/admin-panel/users': '用户管理',
        '/admin-panel/resources': '资源管理',
        '/admin-panel/comments': '评论管理'
      }
      
      const currentRoute = this.$route.path
      return routeMap[currentRoute] ? [routeMap[currentRoute]] : []
    }
  },
  async mounted() {
    this.updateTime()
    this.timeInterval = setInterval(this.updateTime, 1000)
    
    // 检测移动端
    this.checkMobile()
    window.addEventListener('resize', this.handleResize)
    
    // 使用认证工具进行状态检查和恢复
    const { restoreAuthState } = await import('@/utils/auth')
    
    try {
      const result = await restoreAuthState('admin')
      
      if (!result.success) {
        console.log('管理员状态恢复失败:', result.message)
        
        // 延迟跳转，给用户更好的体验
        if (result.message.includes('过期') || result.message.includes('验证失败')) {
          this.$message.warning('登录状态已过期，请重新登录')
        } else {
          this.$message.info('请先登录管理后台')
        }
        
        setTimeout(() => {
          this.$router.push('/admin-login')
        }, 1500)
      } else {
        console.log('管理员状态恢复成功:', result.message)
        // 可以选择显示欢迎消息
        // this.$message.success('欢迎回来！')
      }
    } catch (error) {
      console.error('检查管理员状态时出错:', error)
      this.$message.error('系统初始化失败，请重新登录')
      setTimeout(() => {
        this.$router.push('/admin-login')
      }, 1000)
    }
  },
  beforeDestroy() {
    if (this.timeInterval) {
      clearInterval(this.timeInterval)
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    ...mapMutations(['CLEAR_USER_INFO']),
    
    updateTime() {
      const now = new Date()
      this.currentTime = now.toLocaleTimeString('zh-CN', { 
        hour12: false,
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    toggleSidebar() {
      if (this.isMobile) {
        this.mobileMenuVisible = !this.mobileMenuVisible
      } else {
        this.sidebarCollapsed = !this.sidebarCollapsed
      }
    },
    
    checkMobile() {
      this.isMobile = window.innerWidth <= 768
      if (this.isMobile) {
        this.mobileMenuVisible = false
      }
    },
    
    handleResize() {
      this.checkMobile()
    },
    
    goToHome() {
      this.$router.push('/admin-panel/dashboard')
    },
    

    
    handleCommand(command) {
      if (command === 'logout') {
        this.logout()
      }
    },
    
    async logout() {
      this.$confirm('确定要退出登录吗？', '退出确认', {
        confirmButtonText: '确定退出',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'logout-confirm'
      }).then(async () => {
        try {
          // 调用后端管理员退出接口
          await userApi.adminLogout()
        } catch (error) {
          // 退出登录API调用失败，但继续执行本地清理
        }
        
        // 清除用户信息
        this.CLEAR_USER_INFO()
        // 只清除管理员相关的存储
        localStorage.removeItem('adminUserInfo')
        localStorage.removeItem('adminToken')
        // 向后兼容：清除旧格式（但不影响用户token）
        const hasUser = localStorage.getItem('userToken') || localStorage.getItem('userUserInfo')
        if (!hasUser) {
          localStorage.removeItem('userInfo')
          localStorage.removeItem('token')
        }
        
        this.$message.success('已安全退出登录')
        this.$router.push('/admin-login')
      }).catch(() => {
        // 用户取消
      })
    }
  }
}
</script>

<style scoped>
.admin-layout {
  display: flex;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: #f0f2f5;
}

/* 侧边栏样式 */
.sidebar {
  width: 280px;
  height: 100vh;
  background: linear-gradient(135deg, #1a1f2e 0%, #16213e 50%, #1a1f2e 100%);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  overflow-y: auto;
  overflow-x: hidden;
  box-shadow: 4px 0 20px rgba(0, 0, 0, 0.15);
  position: relative;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  border-right: 1px solid rgba(255, 255, 255, 0.1);
}

.sidebar::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 20% 50%, rgba(64, 158, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(103, 194, 58, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 40% 80%, rgba(245, 108, 108, 0.1) 0%, transparent 50%);
  pointer-events: none;
}

.sidebar.collapsed {
  width: 80px;
}

/* 侧边栏头部 */
.sidebar-header {
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.1) 0%, rgba(51, 126, 204, 0.1) 100%);
  color: white;
  position: relative;
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.logo {
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 12px 20px;
  border-radius: 12px;
}

.logo:hover {
  background: rgba(255, 255, 255, 0.1);
  transform: translateY(-2px);
}

.logo-icon {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.logo-icon .el-icon {
  font-size: 20px;
  color: white;
}

.logo-content {
  display: flex;
  align-items: center;
}

.logo-title {
  font-size: 20px;
  font-weight: 700;
  color: #ffffff;
  line-height: 1.2;
}

/* 折叠状态下的logo样式 */
.sidebar.collapsed .logo {
  justify-content: center;
  padding: 12px 0;
}

.sidebar.collapsed .logo-content {
  display: none;
}



/* 菜单区域 */
.menu-section {
  flex: 1;
  padding: 0 16px;
  overflow-y: auto;
  overflow-x: hidden;
  min-height: 0;
}

/* 折叠状态下调整菜单区域padding */
.sidebar.collapsed .menu-section {
  padding: 0 8px;
}

.menu-title {
  padding: 20px 4px 12px;
  color: #8b949e;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 1px;
}

/* 折叠状态下隐藏菜单标题 */
.sidebar.collapsed .menu-title {
  display: none;
}

.sidebar-menu {
  border: none;
  background: transparent;
  width: 100%;
}

.menu-item {
  margin-bottom: 8px;
  border-radius: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  position: relative;
}

.menu-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.1) 0%, rgba(51, 126, 204, 0.1) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.menu-item:hover::before {
  opacity: 1;
}

.menu-item.is-active::before {
  opacity: 1;
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
}

.menu-item-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 20px;
  position: relative;
  z-index: 1;
}

.menu-icon {
  width: 20px;
  height: 20px;
  font-size: 18px;
  color: #8b949e;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.menu-text {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
  color: #8b949e;
  transition: all 0.3s ease;
}

.menu-indicator {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: transparent;
  transition: all 0.3s ease;
}

.menu-item:hover .menu-icon,
.menu-item:hover .menu-text {
  color: #ffffff;
  transform: translateX(4px);
}

.menu-item.is-active .menu-icon,
.menu-item.is-active .menu-text {
  color: #ffffff;
}

.menu-item.is-active .menu-indicator {
  background: #ffffff;
  box-shadow: 0 0 12px rgba(255, 255, 255, 0.5);
}

/* 折叠状态下的菜单样式 */
.sidebar.collapsed .menu-item {
  margin: 8px 12px;
}

.sidebar.collapsed .menu-item-content {
  justify-content: center;
  padding: 16px 0;
  gap: 0;
}

.sidebar.collapsed .menu-text,
.sidebar.collapsed .menu-indicator {
  display: none;
}

.sidebar.collapsed .menu-icon {
  margin: 0;
  width: 24px;
  height: 24px;
  font-size: 20px;
}

/* 覆盖Element Plus默认的折叠样式 */
.sidebar.collapsed .sidebar-menu.el-menu--collapse .el-menu-item {
  padding: 0 !important;
  text-align: center;
  width: auto;
  min-width: auto;
}

.sidebar.collapsed .sidebar-menu.el-menu--collapse .el-menu-item > * {
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sidebar.collapsed .sidebar-menu.el-menu--collapse .el-menu-item .menu-item-content {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 确保图标在折叠状态下的悬停效果正确 */
.sidebar.collapsed .menu-item:hover .menu-icon {
  transform: none;
  color: #ffffff;
}

/* 强制Element Plus菜单项在折叠状态下居中 */
.sidebar.collapsed .el-menu-item {
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  padding-left: 0 !important;
  padding-right: 0 !important;
  margin: 8px 12px !important;
  border-radius: 12px !important;
}

.sidebar.collapsed .el-menu-item > div {
  width: 100% !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
}

/* 确保折叠状态下的活跃状态显示正确 */
.sidebar.collapsed .el-menu-item.is-active {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%) !important;
}



/* 侧边栏底部 */
.sidebar-footer {
  padding: 20px 16px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  background: linear-gradient(135deg, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0.1) 100%);
}

.footer-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  background: #67c23a;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(103, 194, 58, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
  }
}

.status-text {
  font-size: 12px;
  color: #8b949e;
  font-weight: 500;
}

.system-time {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #8b949e;
  font-size: 12px;
  font-weight: 500;
}

.system-time .el-icon {
  font-size: 14px;
}

.footer-collapsed {
  display: flex;
  justify-content: center;
}

.status-dot-mini {
  width: 6px;
  height: 6px;
  background: #67c23a;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

/* 主内容区域样式 */
.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-left: 0;
  transition: all 0.3s ease;
  min-width: 0;
  overflow: hidden;
}

.main-container.expanded {
  margin-left: 0;
}

/* 顶部导航栏样式 */
.navbar {
  height: 60px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  position: relative;
  z-index: 10;
}

.navbar-left {
  display: flex;
  align-items: center;
  gap: 20px;
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.sidebar-toggle {
  font-size: 18px;
  color: #666;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.sidebar-toggle:hover {
  color: #409eff;
  background-color: #f5f5f5;
}

.sidebar-toggle .el-icon {
  font-size: 16px;
}

.breadcrumb {
  font-size: 14px;
  overflow: hidden;
  white-space: nowrap;
}

.navbar-right {
  display: flex;
  align-items: center;
  gap: 15px;
}



.user-dropdown-container .user-dropdown {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 20px;
  transition: background-color 0.3s ease;
  color: #666;
  border: 1px solid transparent;
}

.user-dropdown:hover {
  background-color: #f5f5f5;
  border-color: #e0e0e0;
}

.user-avatar {
  flex-shrink: 0;
}

.username {
  font-weight: 500;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-dropdown .arrow-down {
  font-size: 12px;
  transition: transform 0.3s ease;
}

.user-dropdown:hover .arrow-down {
  transform: rotate(180deg);
}

/* 主内容样式 */
.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #f0f2f5;
  min-width: 0;
}

/* 下拉菜单样式 */
.el-dropdown-menu .el-dropdown-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
}

.el-dropdown-menu .el-dropdown-item .el-icon {
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .sidebar {
    width: 260px;
  }
  
  .sidebar.collapsed {
    width: 70px;
  }
}

@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    z-index: 1000;
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }
  
  .sidebar.mobile-show {
    transform: translateX(0);
  }
  
  .sidebar.collapsed {
    transform: translateX(-100%);
  }
  
  .main-container {
    margin-left: 0 !important;
  }
  
  .admin-layout {
    flex-direction: column;
  }
  
  .sidebar {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;
    height: 100vh;
    transform: translateX(0);
    transition: transform 0.3s ease;
  }
  
  .sidebar.collapsed {
    transform: translateX(-250px);
  }
  
  .main-container {
    margin-left: 0;
    width: 100%;
  }
  
  .navbar-left .breadcrumb {
    display: none;
  }
  
  .navbar-right {
    gap: 10px;
  }
  
  .username {
    display: none;
  }
}

/* 自定义确认对话框样式 */
:deep(.logout-confirm) {
  border-radius: 12px;
}

:deep(.logout-confirm .el-message-box__header) {
  padding: 20px 20px 10px;
}

:deep(.logout-confirm .el-message-box__content) {
  padding: 10px 20px 20px;
}
</style> 